package com.itlong.cloud.controller.miniprogram;
import com.itlong.cloud.POJO.DTO.app.AppCallLiftSaveDTO;
import com.itlong.cloud.POJO.DTO.app.MiniCallDTO;
import com.itlong.cloud.POJO.DTO.app.MiniCallLiftDTO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.app.AppCallElevatorRecordVO;
import com.itlong.cloud.POJO.VO.app.AppElevatorFloorSimpleVO;
import com.itlong.cloud.POJO.VO.app.AppFloorDevicesVO;
import com.itlong.cloud.POJO.VO.app.AppUserCacheVO;
import com.itlong.cloud.POJO.VO.property.CloudElevatorVO;
import com.itlong.cloud.POJO.VO.property.MiniCloudElevatorRunStateVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.enumerate.CallElevatorSourceTypeEnum;
import com.itlong.cloud.enumerate.CloudElevatorCallTypeEnum;
import com.itlong.cloud.enumerate.CloudElevatorSourceEnum;
import com.itlong.cloud.enumerate.IotDeviceStatusEnum;
import com.itlong.cloud.enumerate.ecode.AppErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.MiniProgramErrorCodeEnum;
import com.itlong.cloud.equip.app.IAppDeviceServiceClient;
import com.itlong.cloud.iottp.IIotServerServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.app.IAppHomeServiceClient;
import com.itlong.cloud.user.miniprogram.IMiniProgramLoginServiceClient;
import com.itlong.cloud.utils.encrypt.Md5EncryptUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.xml.transform.Source;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <desc>
 *     小程序云电梯控制器
 * </desc>
 *
 * @create  2018/11/19
 */
@RestController
@RequestMapping("/cloudElevator")
@RefreshScope
public class MiniprogramCloudElevatorController extends BaseController{

    private static final Logger LOG = LoggerFactory.getLogger(MiniprogramCloudElevatorController.class);

    @Value("${" + PlatformConstants.MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY + "}")
    public String MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY;

    @Autowired
    IMiniProgramLoginServiceClient userCache;

    @Autowired
    IAppHomeServiceClient iAppHomeServiceClient;

    @Autowired
    IAppDeviceServiceClient iAppDeviceServiceClient;

    @Autowired
    IIotServerServiceClient iIotServerServiceClient;
    /**
     * <desc>
     *      获取呼梯记录。
     * <desc/>
     *
     * @param  token 凭证
     * @param deviceUnique 设备唯一ID
     * @return
     * @author Juguang.S
     * @createDate 2018-11-24
     */
    @RequestMapping(value = "/liftMark",method = RequestMethod.POST)
    @ResponseBody
    public Object getCallLiftRecord(String token,String deviceUnique, String createTime, String sign){
        MessageVO messageVO;
        try{
            HttpServletRequest request= ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            token=request.getAttribute("token")==null?null:request.getAttribute("token").toString();
            deviceUnique=request.getAttribute("deviceUnique")==null?null:request.getAttribute("deviceUnique").toString();
            createTime=request.getAttribute("createTime")==null?null:request.getAttribute("createTime").toString();
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("createTime",createTime);
            params.put("deviceUnique",deviceUnique);
            //验证签名
            if(!Md5EncryptUtil.checkAppSignValue(params,sign,MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }
            if(StringUtils.isEmpty(token) || StringUtils.isEmpty(deviceUnique)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }

            //从缓存中获取用户信息
            AppUserCacheVO userInfo=(AppUserCacheVO) StringHandlerUtil.formatString(userCache.retrieve(token));
            List<AppCallElevatorRecordVO> recordVO = iAppHomeServiceClient.getCallElevatorRecord(userInfo.getUserId(),deviceUnique);
            messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),recordVO);
        }catch (Exception e){
            throw new DataAccessException("【微信小程序】获取呼梯记录列表失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      删除呼梯记录。
     * <desc/>
     *
     * @param  token 凭证
     * @param  deviceUnique 设备唯一ID
     * @return
     * @author Juguang.S
     * @createDate 2018-11-24
     */
    @LoggerInfo(operateDesc = LogDescConstant.DELETE_CALL_ELEVATOR)
    @RequestMapping(value = "/deleteLiftMark",method = RequestMethod.POST)
    @ResponseBody
    public Object deleteCallLiftRecord(String token,String deviceUnique, String createTime, String sign){
        MessageVO messageVO;
        try{
            HttpServletRequest request= ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            token=request.getAttribute("token")==null?null:request.getAttribute("token").toString();
            deviceUnique=request.getAttribute("deviceUnique")==null?null:request.getAttribute("deviceUnique").toString();
            createTime=request.getAttribute("createTime")==null?null:request.getAttribute("createTime").toString();
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("createTime",createTime);
            params.put("deviceUnique",deviceUnique);
            //验证签名
            if(!Md5EncryptUtil.checkAppSignValue(params,sign,MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }
            if(StringUtils.isEmpty(token) || StringUtils.isEmpty(deviceUnique)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            //从缓存中获取用户信息
            AppUserCacheVO userInfo=(AppUserCacheVO)StringHandlerUtil.formatString(userCache.retrieve(token));
            iAppHomeServiceClient.deleteCallElevatorRecord(userInfo.getUserId(),userInfo.getCurrentProjectId(),deviceUnique);
            messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【微信小程序】删除呼梯记录失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      获取电梯实时状态。
     * <desc/>
     *
     * @param token 凭证
     * @param createTime 时间
     * @param deviceUniques 设备唯一码列表
     * @param sign 签名
     * @return
     * @author Jiaqi.X
     * @createDate 2018/11/28
     */
    @RequestMapping(value = "/getRunStatus",method = RequestMethod.POST)
    @ResponseBody
    public Object getRunStatus(String token,String createTime,String deviceUniques,String sign){
        MessageVO messageVO;
        try{
            HttpServletRequest request= ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            token=request.getAttribute("token")==null?null:request.getAttribute("token").toString();
            createTime=request.getAttribute("createTime")==null?null:request.getAttribute("createTime").toString();
            deviceUniques=request.getAttribute("deviceUniques")==null?null:request.getAttribute("deviceUniques").toString();
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("createTime",createTime);
            params.put("deviceUniques",deviceUniques);
            //验证签名
            if(!Md5EncryptUtil.checkAppSignValue(params,sign,MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return  new MessageVO(AppErrorCodeEnum.APP_SIGN_ERR.getErrorCode());
            }
            //获取设备编号列表
            String[]  deviceUniqueArr = StringHandlerUtil.splitString(deviceUniques);
            if((deviceUniqueArr==null)||(deviceUniqueArr.length<1)){
                return new MessageVO(AppErrorCodeEnum.DEVICE_UNIQUE_EMPTY_ERR.getErrorCode());
            }
            //从缓存中获取用户信息
            AppUserCacheVO userInfo=(AppUserCacheVO)StringHandlerUtil.formatString(userCache.retrieve(token));
            List<MiniCloudElevatorRunStateVO> eleRunStatesVO = iAppDeviceServiceClient.getCloudElevatorStateForMini(deviceUniques, userInfo.getUserId());
            Map<String,Object> result = new HashMap<>();
            result.put("runStatus",eleRunStatesVO);
            messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),result);
        }catch (Exception e){
            throw new DataAccessException("【APP_首页版块】获取电梯实时状态失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      预约呼梯。
     * <desc/>
     *
     * @param  miniCallDTO 呼梯数据对象
     * @param  sign 签名
     * @param token token
     * @return
     * @author Jiaqi.X
     * @createDate 2018/11/29
     */
    @LoggerInfo(operateDesc = LogDescConstant.CALL_ELEVATOR)
    @RequestMapping(value = "/callElevator",method = RequestMethod.POST)
    @ResponseBody
    public Object callElevator(MiniCallDTO miniCallDTO, String sign,String token){
        MessageVO messageVO;
        try {
            HttpServletRequest request= ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            miniCallDTO= HttpProtocolUtil.parseRequestParamToDTO(MiniCallDTO.class,request);
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            token=request.getAttribute("token")==null?null:request.getAttribute("token").toString();
            //验证签名
            if(!Md5EncryptUtil.checkAppSignValue(miniCallDTO,sign,MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return  new MessageVO(AppErrorCodeEnum.APP_SIGN_ERR.getErrorCode());
            }
            //判断设备唯一编号
            if(StringUtils.isBlank(miniCallDTO.getDeviceUnique())){
                return new MessageVO(AppErrorCodeEnum.DEVICE_UNIQUE_EMPTY_ERR.getErrorCode());
            }
            MiniCallLiftDTO miniCallLiftDTO = JsonUtil.toObject(JsonUtil.toJSON(miniCallDTO),MiniCallLiftDTO.class);
            Map<String,Object> naturalFloor = iAppHomeServiceClient.getNaturalFloor(miniCallLiftDTO.getDeviceUnique(),miniCallLiftDTO.getFromFloor(),miniCallLiftDTO.getToFloor());
            miniCallLiftDTO.setFromId(naturalFloor.get("fromFloor").toString());
            miniCallLiftDTO.setToId(naturalFloor.get("toFloor").toString());
            //判断楼层
            Map result = StringHandlerUtil.checkFloor(miniCallLiftDTO.getFromId(),miniCallLiftDTO.getToId(),PlatformConstants.MAX_FLOOR_NUM);
            if(!"0".equals(result.get("code").toString())){
                return new MessageVO(AppErrorCodeEnum.ELEVATOR_FLOOR_ERROR.getErrorCode(),result.get("message"));
            }
            //从缓存中获取用户信息
            AppUserCacheVO userInfo=(AppUserCacheVO)StringHandlerUtil.formatString(userCache.retrieve(token));
            CloudElevatorVO vo = iAppDeviceServiceClient.getCallElevatorInfo(miniCallDTO.getDeviceUnique());
            //判断当前设备是否在线，如不在线返回失败
            String isOnline = iIotServerServiceClient.batchGetDeviceState(vo.getIotProductKey(),miniCallDTO.getDeviceUnique());
            if(isOnline ==null || (isOnline != null && !isOnline.equals(IotDeviceStatusEnum.ONLINE.getType()))){
                return new MessageVO(AppErrorCodeEnum.CLOUD_ELEVATOR_OUT_LINE.getErrorCode());
            }
            //查询电梯设备是否绑定控制器
            Map<String,Object> controller = iAppDeviceServiceClient.getControllerDeviceUniqueByElevatorDeviceUnique(miniCallDTO.getDeviceUnique());
            //判断群控器是否在线
            if(controller != null && controller.get("groupConId") != null){
                isOnline = iIotServerServiceClient.batchGetDeviceState(controller.get("iotProductKey").toString(),controller.get("groupConId").toString());
                if(isOnline ==null || (isOnline != null && !isOnline.equals(IotDeviceStatusEnum.ONLINE.getType()))){
                    return new MessageVO(AppErrorCodeEnum.CLOUD_ELEVATOR_OUT_LINE.getErrorCode());
                }
            }
            //电梯设备信息
            List<AppFloorDevicesVO> floors=iAppDeviceServiceClient.getFloorDevices(userInfo.getUserId(),miniCallDTO.getProjectId(),1);
            // 获取游客模式下有公共楼层的电梯设备
            List<AppFloorDevicesVO> floorGuestList = iAppDeviceServiceClient.getGuestFloorList(miniCallDTO.getProjectId());
            List<String> floorDeviceUniqueList = new ArrayList<>();
            for (AppFloorDevicesVO appFloorDevicesVO : floors) {
                floorDeviceUniqueList.add(appFloorDevicesVO.getDeviceUnique());
            }
            for (AppFloorDevicesVO appFloorDevicesVO : floorGuestList) {
                if (!floorDeviceUniqueList.contains(appFloorDevicesVO.getDeviceUnique())) {
                    floors.add(appFloorDevicesVO);
                    floorDeviceUniqueList.add(appFloorDevicesVO.getDeviceUnique());
                }
            }
            if((floors!=null)&&(floors.size()>0)){
                Optional<AppFloorDevicesVO> floorInfo = floors.stream().filter(floor->miniCallLiftDTO.getDeviceUnique().equals(floor.getDeviceUnique())).findFirst();
                if(floorInfo.isPresent()){
                    List<String> validFloor=new ArrayList<>(); //合法楼层
                    //常用楼层
                    List<String> liveFloorList = StringHandlerUtil.splitStringList(floorInfo.get().getLiveFloor());
                    if((liveFloorList!=null)&&(liveFloorList.size()>0)){
                        validFloor = liveFloorList.stream().filter(liveFloor->(liveFloor.equals(miniCallLiftDTO.getFromId())||liveFloor.equals(miniCallLiftDTO.getToId()))).collect(Collectors.toList());
                    }
                    //公共楼层
                    List<String> commonFloorList = StringHandlerUtil.splitStringList(floorInfo.get().getCommonFloor());
                    if((commonFloorList!=null)&&(commonFloorList.size()>0)){
                        List<String> tmp = commonFloorList.stream().filter(commonFloor->(commonFloor.equals(miniCallLiftDTO.getFromId())||commonFloor.equals(miniCallLiftDTO.getToId()))).collect(Collectors.toList());
                        validFloor.addAll(tmp);
                    }
                    if((validFloor==null)||((validFloor!=null)&&(validFloor.size()<2))){
                        return new MessageVO(AppErrorCodeEnum.FLOOR_NOT_VALID_ERR.getErrorCode());
                    }
                }else{
                    //该用户该电梯设备信息
                    //LOG.info(String.format("该用户无该电梯设备信息，用户Id：%s 项目编号：%s 设备编号：%s",userInfo.getUserId(),userInfo.getCurrentProjectId(),miniCallLiftDTO.getDeviceUnique()));
                    return new MessageVO(AppErrorCodeEnum.CLOUD_ELEVATOR_OUT_LINE.getErrorCode());
                }
            }else {
                //该用户无任何设备信息
                //LOG.info(String.format("该用户无任何电梯设备信息，用户Id：%s 项目编号：%s",userInfo.getUserId(),userInfo.getCurrentProjectId()));
                return new MessageVO(BaseErrorCodeEnum.ERROR.getErrorCode());
            }
            //取真实楼层
            AppElevatorFloorSimpleVO simpleVO = iAppHomeServiceClient.getRealFloorInfo(miniCallLiftDTO.getDeviceUnique(), miniCallLiftDTO.getFromId(), miniCallLiftDTO.getToId());
            if(simpleVO==null){
                LOG.info(String.format("【首页_预约呼梯】楼层号信息有误，设备号：%s 出发楼层：s%  目标楼层：s%",miniCallLiftDTO.getDeviceUnique(),miniCallLiftDTO.getFromFloor(),miniCallLiftDTO.getToFloor()));
                return new MessageVO(BaseErrorCodeEnum.ERROR.getErrorCode());
            }
            if(null != controller && null != controller.get("deviceUnique") ) {
                String userLabel = iAppDeviceServiceClient.getUserLabel(userInfo.getUserId(), StringHandlerUtil.getProjectIdByDeviceUnique(miniCallDTO.getDeviceUnique()));
                if(StringUtils.isBlank(userLabel) || !userLabel.contains("1")) {
                    Boolean isVipCall = iAppDeviceServiceClient.getIsVipCall(miniCallDTO.getDeviceUnique());
//                    LOG.info("是否处于vip呼梯中》》》》》》》》》》》》》》》》》》" + isVipCall);
                    if(isVipCall) {
                        return new MessageVO(BaseErrorCodeEnum.ELEVATOR_CALL_ERR.getErrorCode());
                    }
                }
            }
            //调用IOT呼梯
            iAppDeviceServiceClient.cloudElevatorCall(miniCallLiftDTO.getDeviceUnique(),
                    CloudElevatorSourceEnum.ITLONG_CLOUD_ELEVATOR.getDescription(),
                    simpleVO.getRealFrom(),simpleVO.getRealTo(),null, CloudElevatorCallTypeEnum.OUT.getType(),null,
                    CallElevatorSourceTypeEnum.APP.getType(),null,null,null, null, null, userInfo.getUserId(), "");
            //装配呼梯记录对象
            AppCallLiftSaveDTO saveDTO = new AppCallLiftSaveDTO();
            saveDTO.setUserId(userInfo.getUserId());
            if(controller != null && controller.get("groupConId") != null){
                saveDTO.setGroupConId(controller.get("groupConId").toString());
            }
            saveDTO.setDeviceUnique(miniCallLiftDTO.getDeviceUnique());
            saveDTO.setFromFloor(miniCallLiftDTO.getFromId());
            saveDTO.setToFloor(miniCallLiftDTO.getToId());
            saveDTO.setProjectId(miniCallLiftDTO.getProjectId());

            if(null != miniCallDTO.getSource()) {
                saveDTO.setSource(miniCallDTO.getSource());
            }else {
                saveDTO.setSource(3);
            }

            iAppHomeServiceClient.saveCallLiftRecord(saveDTO);
            messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【小程序_云电梯】预约呼梯",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      取消预约呼梯。
     * <desc/>
     *
     * @param  deviceUnique 设备唯一编码
     * @param  token 凭证
     * @param  createTime 时间
     * @param  sign 签名
     * @return
     * @author Jiaqi.X
     * @createDate 2018/11/29
     */
    @LoggerInfo(operateDesc = LogDescConstant.CALL_OFF_ELEVATOR)
    @RequestMapping(value = "/callOffTheElevator",method = RequestMethod.POST)
    @ResponseBody
    public Object callOffTheElevator(String deviceUnique,String token,String createTime,String sign,String projectId){
        MessageVO messageVO;
        try {
            HttpServletRequest request= ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            deviceUnique=request.getAttribute("deviceUnique")==null?null:request.getAttribute("deviceUnique").toString();
            token=request.getAttribute("token")==null?null:request.getAttribute("token").toString();
            createTime=request.getAttribute("createTime")==null?null:request.getAttribute("createTime").toString();
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            projectId=request.getAttribute("projectId")==null?null:request.getAttribute("projectId").toString();
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("createTime",createTime);
            params.put("deviceUnique",deviceUnique);
            params.put("projectId",projectId);
            //验证签名
            if(!Md5EncryptUtil.checkAppSignValue(params,sign,MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return  new MessageVO(AppErrorCodeEnum.APP_SIGN_ERR.getErrorCode());
            }
            //判断设备唯一编号
            if(StringUtils.isBlank(deviceUnique)){
                return new MessageVO(AppErrorCodeEnum.DEVICE_UNIQUE_EMPTY_ERR.getErrorCode());
            }
            //从缓存中获取用户信息
            AppUserCacheVO userInfo=(AppUserCacheVO)StringHandlerUtil.formatString(userCache.retrieve(token));
            //取消预约呼梯
            iAppHomeServiceClient.cancelCallLift(userInfo.getUserId(),projectId,deviceUnique);
            messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【小程序_云电梯】取消预约呼梯",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      单楼层呼梯（内呼）
     * <desc/>
     *
     * @param token
     * @param deviceUnique
     * @param logicalFloor
     * @return
     * @author Jiaqi.X
     * @createDate 2019/08/29
     */
    @LoggerInfo(operateDesc = LogDescConstant.IN_CALL_ELEVATOR)
    @RequestMapping(value = "/inCall",method = RequestMethod.POST)
    @ResponseBody
    public Object inCall(String token,String deviceUnique,String logicalFloor,String correlationId,String createTime,String sign) {
        try {
            HttpServletRequest request= ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            token=request.getAttribute("token")==null?null:request.getAttribute("token").toString();
            deviceUnique=request.getAttribute("deviceUnique")==null?null:request.getAttribute("deviceUnique").toString();
            logicalFloor=request.getAttribute("logicalFloor")==null?null:request.getAttribute("logicalFloor").toString();
            correlationId=request.getAttribute("correlationId")==null?null:request.getAttribute("correlationId").toString();
            createTime=request.getAttribute("createTime")==null?null:request.getAttribute("createTime").toString();
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("createTime",createTime);
            params.put("deviceUnique",deviceUnique);
            params.put("logicalFloor",logicalFloor);
            //验证签名
            if(!Md5EncryptUtil.checkAppSignValue(params,sign,MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return  new MessageVO(AppErrorCodeEnum.APP_SIGN_ERR.getErrorCode());
            }
            CloudElevatorVO vo = iAppDeviceServiceClient.getCallElevatorInfo(deviceUnique);
            //判断当前设备是否在线，如不在线返回失败
            String isOnline = iIotServerServiceClient.batchGetDeviceState(vo.getIotProductKey(),deviceUnique);
            if(isOnline ==null || (isOnline != null && !isOnline.equals(IotDeviceStatusEnum.ONLINE.getType()))){
                return new MessageVO(AppErrorCodeEnum.CLOUD_ELEVATOR_OPEN_ERROR.getErrorCode());
            }
            //获取真实楼层
            Map<String,Object> floor = iAppDeviceServiceClient.getFloorNumAndNaturalFloorByLogicFloor(logicalFloor,
                    deviceUnique);
            if(floor ==null || floor.get("floors") ==null || floor.get("naturals") == null){
                return new MessageVO(AppErrorCodeEnum.ELEVATOR_FLOOR_ERROR.getErrorCode());
            }
            AppUserCacheVO userInfoPo=(AppUserCacheVO)StringHandlerUtil.formatString(userCache.retrieve(token));
            //调用IOT呼梯
            iAppDeviceServiceClient.openOrAutoRegister(deviceUnique,
                    CloudElevatorSourceEnum.ITLONG_CLOUD_ELEVATOR.getDescription(),
                    floor.get("floors").toString(),  CloudElevatorCallTypeEnum.IN.getType(),0, CallElevatorSourceTypeEnum.MINIPROGRAM.getType(),null, userInfoPo.getUserId());

            String finalToken = token;
            String finalDeviceUnique = deviceUnique;
            String finalCorrelationId = correlationId;
            new Thread(()->{
                try {
                    //此处休眠3秒是便于蓝牙呼梯通行记录的上传
                    Thread.sleep(3000);
                    //装配保存通行记录对象
                    AppUserCacheVO userInfo=(AppUserCacheVO)StringHandlerUtil.formatString(userCache.retrieve(finalToken));
                    AppCallLiftSaveDTO saveDTO = new AppCallLiftSaveDTO();
                    saveDTO.setUserId(userInfo.getUserId());
                    saveDTO.setDeviceUnique(finalDeviceUnique);
                    saveDTO.setProjectId(finalDeviceUnique.substring(0,8));
                    saveDTO.setMark(1);
                    saveDTO.setCorrelationId(finalCorrelationId);
                    saveDTO.setSource(2);
                    iAppHomeServiceClient.saveCallLiftRecord(saveDTO);
                } catch (Exception e) {
                    throw new DataAccessException("【小程序】内呼异常", e);
                }
            }).start();

            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【小程序】内呼异常", e);
        }
    }
}
